package com.zm.devmag.base.destroy;

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.mysql.jdbc.AbandonedConnectionCleanupThread;
import com.zm.devmag.device.dao.IOStockTempMapper;
import com.zm.devmag.device.dao.TempDataMapper;






@WebListener
public class ContextFinalizer implements ServletContextListener {

	private static final Logger logger = LoggerFactory
			.getLogger(ContextFinalizer.class);

	private Timer timerdelsql = new Timer();
	@Autowired
	private TempDataMapper tMapper;
	@Autowired
	private IOStockTempMapper iostMapper;
	
	public void contextInitialized(ServletContextEvent sce) {
		logger.info("[项目启动。。。。]");
		WebApplicationContextUtils
				.getRequiredWebApplicationContext(sce.getServletContext())
				.getAutowireCapableBeanFactory().autowireBean(this);
		SimpleDateFormat dateFormatter = new SimpleDateFormat(
				"yyyy/MM/dd HH:mm:ss");
		Date startDate = null;
		try {
			startDate = dateFormatter.parse("2010/11/28 03:30:00");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		timerdelsql.schedule(new TimerTask() {
			public void run() {
				/* System.out.println("定时器启动timerdelsql"); */
				if (0 <= tMapper.deleteAll()) {
					System.out.println("清除没临时数据tMapper:::::::::"
							+ System.currentTimeMillis() / 1000);
				}
				if (0 <= iostMapper.deleteAll()) {
					System.out.println("清除没临时数据iostMapper:::::::::"
							+ System.currentTimeMillis() / 1000);
				}
			}
		}, startDate, 86400 * 1000);
		
	}



	public void contextDestroyed(ServletContextEvent sce) {
		Enumeration<Driver> drivers = DriverManager.getDrivers();
		Driver d = null;
		
		while (drivers.hasMoreElements()) {
			try {
				d = drivers.nextElement();
				DriverManager.deregisterDriver(d);
				logger.warn(String.format("Driver %s deregistered", d));
			} catch (SQLException ex) {
				logger.warn(String.format("Error deregistering driver %s", d),
						ex);
			}
		}
		try {
			AbandonedConnectionCleanupThread.shutdown();
		} catch (InterruptedException e) {
			logger.warn("SEVERE problem cleaning up: " + e.getMessage());
			e.printStackTrace();
		}
		this.timerdelsql.cancel();
	}
}
